package com.framework.web.sys.util;

import com.framework.core.annotation.SpringContextHolder;
import com.framework.core.constant.Globals;
import com.framework.core.domain.SessionVo;
import com.framework.web.sys.domain.Log;
import com.framework.web.sys.repository.LogRepository;
import com.framework.web.sys.service.LogService;
import org.springframework.http.HttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.StringTokenizer;

/**
 * Created by fusf on 2016/5/28.
 */
public class LogThreadUtil {

    /**
     * 登录登出日志
     * @param sessionVo
     * @param request
     */
    public static void saveLoginLog(final SessionVo sessionVo,final HttpServletRequest request,final String logType) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log log = new Log();
                    log.setUserId(sessionVo.getUserId());
                    log.setUserName(sessionVo.getUserName());
                    log.setRealName(sessionVo.getRealName());
                    log.setLogType(logType);//日志类型
                    log.setIpAddress(request.getRemoteAddr());//ip地址
                    String Agent = request.getHeader("User-Agent");
                    StringTokenizer st = new StringTokenizer(Agent, ";");
                    st.nextToken();
                    //得到用户的浏览器名
                    String userBrowser = st.nextToken();
                    log.setBrowserType(userBrowser);
                    log.setBrowserInfo(Agent);
                    String msg = "登出成功";
                    if (Globals.LOG_TYPE_LOGIN.equals(logType)) {
                        msg = "登录成功";
                    }
                    log.setOperationInfo(msg);
                    log.setOperateTime(new Date());
                    LogService logService = (LogService) SpringContextHolder.getBean("logService");
                    logService.save(log);
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
